package cn.orange.ch01_array.binarysearch;

/**
 * LC69.x 的平方根
 给你一个非负整数 x ，计算并返回 x 的算术平方根
 由于返回类型是整数，结果只保留整数部分 ，小数部分将被舍去
 */
public class LC69 {
    public int mySqrt(int x) {
        int i = 0;
        int j = x;
        int ans = -1;
        while (i <= j) {
            int mid = i + (j - i) / 2;
            long sqt = (long) mid * mid;
            if (sqt > (long) x) {
                j = mid - 1;
            } else {
                ans = mid;
                i = mid + 1;
            }
        }
        return ans;
    }
    public static void main(String[] args) {
        LC69 alg = new LC69();
        System.out.println(alg.mySqrt(0));
        System.out.println(alg.mySqrt(1));
        System.out.println(alg.mySqrt(8));
        System.out.println(alg.mySqrt(4));
    }
}
